package com.yanjiali.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanjiali.constant.OneDirNameConstant;
import com.yanjiali.entity.EncryptCollectUser;
import com.yanjiali.mapper.EncryptCollectUserMapper;
import com.yanjiali.model.R;
import com.yanjiali.model.req.UpdatePasswordReq;
import com.yanjiali.model.req.ValidatePasswordReq;
import com.yanjiali.model.resp.GetSecondLevelCollectListByIdResp;
import com.yanjiali.model.resp.UpdatePasswordResp;
import com.yanjiali.model.resp.ValidatePasswordResp;
import com.yanjiali.service.EncryptCollectUserService;
import com.yanjiali.service.SecondLevelCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
* @Package: com.yanjiali.service.impl
* @Author: yanjiali
* @Created: 2025/4/26 18:44
*/
@Service
public class EncryptCollectUserServiceImpl extends ServiceImpl<EncryptCollectUserMapper, EncryptCollectUser> implements EncryptCollectUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SecondLevelCollectService secondLevelCollectService;

    @Override
    public R<ValidatePasswordResp> validatePassword(ValidatePasswordReq validatePasswordReq) {
        if(passwordVerify(validatePasswordReq.getEnterPassword()) != null) {
            R<GetSecondLevelCollectListByIdResp> respR = secondLevelCollectService.getSecondLevelCollectListByName(OneDirNameConstant.DEFAULT_ENCRYPTED);
            if(respR.getCode() == 200) {    //返回对应加密收藏夹中的二级收藏目录
                return R.ok(new ValidatePasswordResp(respR.getData().getSecondLevelCollectList()));
            }
        }

        return R.fail("密码验证失败");
    }

    @Override
    public R<UpdatePasswordResp> updatePassword(UpdatePasswordReq updatePasswordReq) {
        EncryptCollectUser encryptCollectUser = passwordVerify(updatePasswordReq.getOldPassword());
        if(encryptCollectUser != null) {
            //插入新密码
            String newPassword = passwordEncoder.encode(updatePasswordReq.getNewPassword());
            encryptCollectUser.setPassword(newPassword);

            LambdaUpdateWrapper<EncryptCollectUser> luq = new LambdaUpdateWrapper<>();
            luq.eq(EncryptCollectUser::getId, encryptCollectUser.getId());

            boolean update = update(encryptCollectUser, luq);
            if(update) {
                return R.ok(new UpdatePasswordResp("密码修改成功"));
            }
        }

        return R.fail(new UpdatePasswordResp("旧密码错误"));
    }

    /**
     * 密码校验
     * @param inputPassword
     * @return 返回校验结果
     */
    private EncryptCollectUser passwordVerify(String inputPassword) {
        String userId = "";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null) {
            userId = authentication.getPrincipal().toString();
        }else {
            throw new RuntimeException("用户未登录");
        }

        //获取数据库中对应用户的密码
        LambdaQueryWrapper<EncryptCollectUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EncryptCollectUser::getUserId, userId);

        EncryptCollectUser encryptCollectUser = getOne(lambdaQueryWrapper);
        if(encryptCollectUser == null) {
            throw new RuntimeException("用户未设置隐私收藏夹密码");
        }

        boolean matches = passwordEncoder.matches(inputPassword, encryptCollectUser.getPassword());
        if(matches) {
            return encryptCollectUser;
        }

        return null;
    }
}
